import java.util.concurrent.Semaphore;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 17655
 * Date: 2025-03-25
 * Time: 14:57
 */
public class test2 {
    private static final int MAX_VALUE = 200;

    private static int count = 0;

    // 创建两个信号量
    // 除湿量代表一次执行多少次
    private static Semaphore semaphore1 = new Semaphore(1);
    private static Semaphore semaphore2 = new Semaphore(0);


    public static void main(String[] args) {
        Thread t1 = new Thread(() ->{
           while(count<MAX_VALUE){
               try{
                   semaphore1.acquire();
                   if(count<=MAX_VALUE){
                       System.out.println("t1:"+count);
                       count++;
                   }
                   // semaphore1每次打印之后释放semaphore2的许可，使线程2运行
                   semaphore2.release();
               }catch (Exception e){
                    e.printStackTrace();
               }
           }
        });

        Thread t2 = new Thread(() ->{
           while (count<=MAX_VALUE){
               try{
                   semaphore2.acquire();
                   if(count<=MAX_VALUE){
                       System.out.println("t2:"+count);
                       count++;
                   }
                   semaphore1.release();
               }catch (Exception e){
                   e.printStackTrace();
               }
           }
        });

        t1.start();
        t2.start();
    }
}
